<template>
  <div class="manageTablePage">
    <div
      v-for="(center, centerIndex) in tableData"
      :key="center.centerName"
      class="centerItem"
    >
      <div class="centerItemTitle">
        {{ numberToChinese(centerIndex + 1) }}、{{ center.centerName }}
      </div>
      <div class="instructTable" style="height: 600px">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <Sort
              :tableData="
                getTableData(center.robotInstructModuleDTOS, center.centerName)
              "
              v-slot="slotProps"
            >
              <el-table-v2
                :columns="columns"
                :data="slotProps.tableData"
                style="margin-top: 20px"
                :width="width"
                :height="height"
                :row-height="80"
                :sort-by="slotProps.sortState"
                @column-sort="slotProps.onSort"
                fixed
              >
              </el-table-v2>
            </Sort>
          </template>
        </el-auto-resizer>
      </div>
    </div>
    <el-empty :image-size="100" v-if="tableData.length === 0" />

    <el-dialog v-model="describeDialogVisible" title="填写备注" width="500">
      <el-input
        v-model="describeDialogContent"
        type="textarea"
        class="describe_textarea"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="describeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDescribeSubmit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="tsx">
import {
  api_highOrLow,
  api_setInstructDisplay,
  openorclose,
} from "@/api/manage";
import {
  Column,
  ElButton,
  ElMessage,
  ElSwitch,
  TableV2FixedDir,
} from "element-plus";
import { cloneDeep } from "lodash-es";
import { computed, ref } from "vue";
import {
  ECenter,
  EFunctionType,
  EInputDevice,
  EInstructType,
  ERole,
  EVersion,
  EInstructType02
} from "../enum";
import permission from "../permission";
import { formatTableCommonSentence, numberToChinese } from "../utils";
import Sort from "./Sort.vue";
import TableOperation from "./TableOperation.vue";
import type { ITableRow } from "./type";

const props = defineProps<{
  tableData: any[];
  editInstructs: (index: number, row: any) => void;
  deleteInstructs: (index: number, row: any) => void;
  refresh: () => void;
  changeInstructOpenType: (v: string) => void;
  changeInstructIsHigh: (v: string) => void;
  changeInstructDisplay: (v: string) => void;
  addInstructDescribe: (v: { describe: string }) => void;
}>();

const describeDialogVisible = ref(false); //备注弹窗【是否可见】
const describeDialogContent = ref(""); //备注弹窗【内容】
const describeSelectInstruct = ref({} as ITableRow); //备注弹窗对应的【指令对象】

const columns: Column<any>[] = [
  {
    key: "serialNumber",
    dataKey: "serialNumber",
    title: "序号",
    width: 80,
    fixed: TableV2FixedDir.LEFT,
    cellRenderer: ({ rowIndex }) => `${rowIndex + 1}`,
  },
  {
    key: "moduleName",
    dataKey: "moduleName",
    title: "系统/模块名称",
    width: 130,
    fixed: TableV2FixedDir.LEFT,
    cellRenderer: ({ rowData }) => (
      <div className="autoHeight">{rowData?.moduleName}</div>
    ),
  },
  {
    key: "instructCode",
    dataKey: "instructCode",
    title: "指令Code",
    width: 150,
    fixed: TableV2FixedDir.LEFT,
    cellRenderer: ({ rowData }) => (
      <div>
        <span>{rowData.instructCode}</span>
      </div>
    ),
  },
  {
    key: "instructName",
    dataKey: "instructName",
    title: "功能/数据名称",
    width: 150,
    fixed: TableV2FixedDir.LEFT,
    cellRenderer: ({ rowData }) => (
      <div style="overflow: auto">
        <span title={rowData.instructCode}>{rowData.instructName}</span>
        <br />
        {rowData?.moduleId?.trim() && <span>({rowData.moduleId})</span>}
      </div>
    ),
  },
  {
    key: "role",
    dataKey: "role",
    title: "所属角色",
    width: 140,
    cellRenderer: ({ rowData }) => (
      <div className="autoHeight">{rowData?.role}</div>
    ),
  },
  // {
  //   key: "instructInfo",
  //   dataKey: "instructInfo",
  //   title: "指令信息",
  //   width: 240,
  //   cellRenderer: ({ rowData }) => (
  //     <div className="autoHeight">
  //       <ul>
  //         <li>{rowData?.role}</li>
  //         <li>{rowData?.version}</li>
  //         <li>{rowData?.inputDevice}</li>
  //         <li>{rowData?.instructType}</li>
  //       </ul>

  //     </div>
  //   ),
  // },
  {
    key: "version",
    dataKey: "version",
    title: "学年阶段",
    width: 160,
  },
  {
    key: "inputDevice",
    dataKey: "inputDevice",
    title: "支持设备",
    width: 120,
  },
  {
    key: "instructType",
    dataKey: "instructType",
    title: "交互方式",
    width: 100,
  },
  {
    key: "keyword",
    dataKey: "keyword",
    title: "指令关键词",
    width: 160,
    cellRenderer: ({ rowData }) => (
      <div className="autoHeight">{rowData?.keyword}</div>
    ),
  },
  {
    key: "commonSentence",
    dataKey: "commonSentence",
    title: "常用命令词",
    width: 170,
    cellRenderer: ({ rowData }) => (
      <div className="autoHeight">
        {formatTableCommonSentence(rowData.commonSentence).map((v, i) => (
          <div key={i}>{v}</div>
        ))}
      </div>
    ),
  },
  {
    key: "intent",
    dataKey: "intent",
    title: "bert信息",
    width: 160,
    cellRenderer: ({ rowData }) => (
      <div className="autoHeight">
        {rowData?.intent}<br></br>
        {rowData?.domainListStr}
      </div>
    ),
  },
  // {
  //   key: "count",
  //   dataKey: "count",
  //   title: "频次",
  //   width: 90,
  //   sortable: true,
  // },
  {
    key: "isHigh",
    dataKey: "isHigh",
    title: "高频",
    width: 80,
    cellRenderer: ({ rowIndex, rowData }) => (
      <div>
        <ElSwitch
          v-model={rowData.isHigh}
          style={{
            "--el-switch-on-color": "#13ce66",
            "vertical-align": "-3px",
          }}
          onClick={() => highInstructs(rowIndex, rowData)}
        />
      </div>
    ),
  },
  {
    key: "display",
    dataKey: "display",
    title: "对外展示",
    width: 100,
    cellRenderer: ({ rowIndex, rowData }) => (
      <div>
        <ElSwitch
          v-model={rowData.display}
          style={{
            "--el-switch-on-color": "#13ce66",
            "vertical-align": "-3px",
          }}
          onClick={() => displayInstructs(rowIndex, rowData)}
        />
      </div>
    ),
  },
  {
    key: "describe",
    dataKey: "describe",
    title: "备注",
    width: 250,
    cellRenderer: ({ rowData }) => (
      <div className="autoHeight">{rowData?.describe}</div>
    ),
  },
  {
    key: "operation",
    title: "操作",
    width: 160,
    fixed: TableV2FixedDir.RIGHT,
    cellRenderer: ({ rowIndex, rowData }) => (
      /**
       * 直接用jsx会报错 [ElOnlyChild] no valid child node found
       * 应该是el-popconfirm的问题，只能先封装一个组件
       */
      <TableOperation
        open={{ isShow: getPermission(rowData, "canClose") }}
        edit={{ isShow: getPermission(rowData, "canEdit") }}
        delete={{ isShow: getPermission(rowData, "canDelete") }}
        rowData={rowData}
        onOpenInstruct={() => openInstructs(rowIndex, rowData)}
        onEditInstruct={() => editInstructs(rowIndex, rowData)}
        onDeleteInstruct={() => deleteInstructs(rowIndex, rowData)}
        onHandleDescribe={() => handleDescribe(rowIndex, rowData)}
      ></TableOperation>
    ),
  },
];

// 清除robotInstructNameAndSentenceDTOS长度为0的数据
const tableData = computed(() => {
  const arr = cloneDeep(props.tableData);
  for (let i = 0; i < arr.length; i++) {
    const v = arr?.[i];
    for (let j = 0; j < v.robotInstructModuleDTOS?.length; j++) {
      const curModuleInstructs = v.robotInstructModuleDTOS?.[j];
      if (curModuleInstructs.robotInstructNameAndSentenceDTOS?.length === 0) {
        v.robotInstructModuleDTOS.splice(j, 1);
        j--;
      }
    }
  }
  return arr || [];
});

const highInstructs = async (index, row: ITableRow) => {
  const res = await api_highOrLow({
    instructCode: row.instructCode,
    isHigh: row.isHigh ? "1" : "0",
  });
  if (res.success === true) {
    console.log("row.isHigh = ", row.isHigh);
    ElMessage.success(row.isHigh ? "加入高频成功" : "移除高频成功");
    props.changeInstructIsHigh(row.instructCode);
  } else {
    ElMessage.error("请求失败,接口返回:" + res.msg);
  }
};

const displayInstructs = async (index, row: ITableRow) => {
  const res = await api_setInstructDisplay({
    instructCode: row.instructCode,
    display: row.display ? "1" : "0",
  });

  if (res.success === true) {
    ElMessage.success(row.display ? "设置成功" : "已取消对外展示");
    props.changeInstructDisplay(row.instructCode);
  } else {
    ElMessage.error("请求失败,接口返回:" + res.msg);
  }
};

const openInstructs = async (index, row: ITableRow) => {
  const res = await openorclose({
    instructCode: row.instructCode,
    flag: row.flag === 0 ? 1 : 0,
  });
  if (res.success === true) {
    ElMessage.success(row.flag === 0 ? "关闭成功" : "启用成功");
    props.changeInstructOpenType(row.instructCode);
  } else {
    ElMessage.error("请求失败,接口返回:" + res.msg);
  }
};

const editInstructs = (index: number, row: ITableRow) => {
  props.editInstructs(index, row);
};

const deleteInstructs = (index: number, row: ITableRow) => {
  props.deleteInstructs(index, row);
};

/**
 * 弹出备注框
 */
const handleDescribe = (index, row: ITableRow) => {
  describeDialogVisible.value = true;
  describeDialogContent.value = row?.describe;
  describeSelectInstruct.value = row;
};

/**
 * 提交备注
 */
const handleDescribeSubmit = () => {
  const describe = describeDialogContent.value;

  describeDialogVisible.value = false;
  describeSelectInstruct.value.describe = describe;

  props.addInstructDescribe(describeSelectInstruct.value);
};

const getPermission = (row: ITableRow, permissionType) => {
  const p = permission.find((v) => v.instructCode === row.instructCode);
  if (!p) return true;
  if (p?.[permissionType] === undefined) {
    return true;
  }
  return p[permissionType] === true;
};

const getTableData = (moduleInfos, centerName: string): ITableRow[] => {
  const getItem = (name, item, i) => {
    const centerId = Object.keys(ECenter).find((v) => ECenter[v] == centerName);
    // 表格每一行的数据，会传给右侧弹出的抽屉
    return {
      ...item,
      serialNumber: i + 1,
      centerId: centerId,
      moduleName: name,
      instructType: EInstructType[item.instructType],
      role: ERole[item.role],
      version: EVersion[item.version],
      functionType: EFunctionType[item.functionType] || "其它",
      isHigh: item.isHigh === "1",
      display: item.display === "1",
      isInner: item.isInner === '1',
      inputDevice: EInputDevice[item.inputDevice],
      instructType02: EInstructType02[item.instructType02],
      id: item.instructCode, // 每一列的id，用于鼠标hover的时候高亮这一列
    };
  };
  const res = moduleInfos?.map((moduleInfo, i) => {
    return moduleInfo?.robotInstructNameAndSentenceDTOS?.map((v) => {
      return getItem(moduleInfo.moduleName, v, i);
    });
  });
  return res.flat();
};
</script>

<style lang="scss" scoped>
.manageTablePage {
  height: 100%;
  overflow: auto;
  .centerItem {
    margin-bottom: 30px;
    .centerItemTitle {
      font-weight: 700;
    }
  }
  :deep() {
    // 开关组件取消动画
    .el-switch {
      * {
        transition: none;
      }
    }
    // 纯文字的表格项超出有滚动
    .autoHeight {
      width: 100%;
      max-height: 100%;
      white-space: unset;
      overflow: auto;
    }
    .el-table-v2__header-row,
    .el-table-v2__header-cell {
      background-color: #d9d9d9;
      color: #5c5454;
    }
    // element plus的固定列会有滚动条出现，要把它隐藏
    .el-table-v2__left {
      .el-vl__vertical {
        display: none;
      }
    }
  }
}
/**
  el-input的textarea，只能通过这种方式设置高度
*/
.describe_textarea {
  :deep(.el-textarea__inner) {
    height: 300px;
  }
}
</style>
